﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace remes.BLoc.UI
{
   public delegate void StdOutputExecutionDelegate(StdOutLineDelegate stdOutputCallback);

   /// <summary>
   /// Interaction logic for StdOutputWindow.xaml
   /// </summary>
   public partial class StdOutputWindow : Window
   {
      public StdOutputWindow()
      {
         ExecutionCallback = null;
         InitializeComponent();
      }

      public string Description
      {
         get { return (string)GetValue(DescriptionProperty); }
         set { SetValue(DescriptionProperty, value); }
      }

      // Using a DependencyProperty as the backing store for Description.  This enables animation, styling, binding, etc...
      public static readonly DependencyProperty DescriptionProperty =
          DependencyProperty.Register("Description", typeof(string), typeof(StdOutputWindow), new UIPropertyMetadata(String.Empty));

      private void OutputCallback(string line)
      {
         if (!Dispatcher.CheckAccess())
         {
            Dispatcher.Invoke(new StdOutLineDelegate((line_) =>
               {
                  OutputCallback(line_);
               }), line);
         }
         else
         {
            if (IsLoaded)
            {
               if (line == null)
               {
                  line = String.Empty;
               }
               OutputTextBox.Text += line + "\n";
               OutputTextBox.ScrollToEnd();
            }
         }
      }

      public StdOutputExecutionDelegate ExecutionCallback { get; set; }

      private void CloseButton_Click(object sender, RoutedEventArgs e)
      {
         Close();
      }

      private delegate void NoArgsDelegate();

      private void Window_Loaded(object sender, RoutedEventArgs e)
      {
         if (ExecutionCallback != null)
         {
            ThreadPool.QueueUserWorkItem(new WaitCallback((dummy) =>
               {
                  try
                  {
                     ExecutionCallback(OutputCallback);
                  }
                  catch (Exception ex)
                  {
                     OutputCallback("Execution failed:");
                     OutputCallback(ex.Message);
                  }
                  Dispatcher.Invoke(new NoArgsDelegate(() =>
                     {
                        CloseButton.IsEnabled = true;
                     }), null);
               }), null);
         }
      }
   }
}
